package com.grass.appointment.model;

import android.text.TextUtils;
import androidx.core.app.NotificationCompat;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.androidx.p013lv.base.BaseSdk;
import com.androidx.p013lv.base.http.BaseRes;
import com.androidx.p013lv.base.http.HttpUtils;
import com.androidx.p013lv.base.http.UrlManager;
import com.androidx.p013lv.base.http.callback.HttpCallback;
import com.androidx.p013lv.base.interfaces.Key;
import com.androidx.p013lv.base.utils.BuildConfigUtils;
import com.androidx.p013lv.base.utils.DeviceIDUtils;
import com.androidx.p013lv.base.utils.JsonUtils;
import com.androidx.p013lv.base.utils.LogUtils;
import com.androidx.p013lv.base.utils.SpUtils;
import com.google.android.exoplayer2.metadata.icy.IcyHeaders;
import com.google.gson.Gson;
import com.grass.appointment.bean.AddVideoBean;
import com.grass.appointment.bean.CutBean;
import com.grass.appointment.bean.ReqAddVideoBean;
import com.grass.appointment.bean.ReqVideoOkBen;
import com.grass.appointment.bean.SendVideoBean;
import com.grass.appointment.utils.FileListUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.PostRequest;
import com.yalantis.ucrop.view.CropImageView;
import java.io.File;
import java.net.SocketTimeoutException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import okhttp3.OkHttpClient;
import p000a.lzy.p004a.OkUpload;
import p000a.lzy.p004a.upload.UploadListener;
import p000a.lzy.p004a.upload.UploadTask;

public class SendModel extends ViewModel {
    private final String TAG = getClass().getSimpleName();
    private MutableLiveData<BaseRes<AddVideoBean>> addViewData;
    private MutableLiveData<BaseRes<SendVideoBean>> data;
    private File file;
    private String fileMD5;
    private boolean isError = false;
    private List<CutBean> list;
    private OkHttpClient okHttpClient;
    private String taskId;

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void delete() {
    }

    public MutableLiveData<BaseRes<SendVideoBean>> getMutableLiveData() {
        if (this.data == null) {
            this.data = new MutableLiveData<>();
        }
        return this.data;
    }

    public MutableLiveData<BaseRes<AddVideoBean>> getVideoMutableLiveData() {
        if (this.addViewData == null) {
            this.addViewData = new MutableLiveData<>();
        }
        return this.addViewData;
    }

    public void send(final String str) {
        new Thread(new Runnable() {
            /* class com.grass.appointment.model.SendModel.RunnableC28491 */

            public void run() {
                SendModel.this.isError = false;
                SendModel.this.file = new File(str);
                SendModel sendModel = SendModel.this;
                sendModel.execute(sendModel.file);
            }
        }).start();
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void execute(File file2) {
        if (this.okHttpClient == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.readTimeout(500, TimeUnit.SECONDS);
            builder.writeTimeout(500, TimeUnit.SECONDS);
            builder.connectTimeout(500, TimeUnit.SECONDS);
            if (BuildConfigUtils.isIsDebug()) {
                HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor("OkGo");
                httpLoggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
                httpLoggingInterceptor.setColorLevel(Level.INFO);
                builder.addInterceptor(httpLoggingInterceptor);
            }
            this.okHttpClient = builder.build();
        }
        this.fileMD5 = FileListUtils.getFileMD5s(file2, 32);
        try {
            LogUtils.m63e("ddddddddddddd", file2.getAbsolutePath() + "<---" + file2.length());
            this.list = FileListUtils.fileList(this.fileMD5, file2);
            this.taskId = FileListUtils.getMD5(System.currentTimeMillis() + "");
            addUploadTask();
        } catch (Exception e) {
            e.printStackTrace();
            this.data.setValue(new BaseRes<>(CropImageView.DEFAULT_IMAGE_TO_CROP_BOUNDS_ANIM_DURATION, "分片失敗"));
            delete();
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void addUploadTask() {
        String urlSend = UrlManager.getInsatance().urlSend();
        for (int i = 0; i < this.list.size(); i++) {
            CutBean cutBean = this.list.get(i);
            LogUtils.m63e("ddddddddddddd", cutBean.getPath() + "<---" + new File(cutBean.getPath()).length());
            File file2 = new File(cutBean.getPath());
            String str = this.taskId;
            int tag = cutBean.getTag();
            C28502 r6 = new HttpCallback<BaseRes<SendVideoBean>>("" + cutBean.getTag()) {
                /* class com.grass.appointment.model.SendModel.C28502 */

                public void onLvSuccess(BaseRes<SendVideoBean> baseRes) {
                }
            };
            post_form(urlSend, file2, str, tag, r6, new UploadListener<BaseRes<SendVideoBean>>("" + cutBean.getTag()) {
                /* class com.grass.appointment.model.SendModel.C28513 */

                @Override // p000a.lzy.p004a.ProgressListener
                public void onRemove(Progress progress) {
                }

                @Override // p000a.lzy.p004a.ProgressListener
                public void onStart(Progress progress) {
                }

                @Override // p000a.lzy.p004a.ProgressListener
                public void onProgress(Progress progress) {
                    SendModel.this.progress(progress);
                }

                @Override // p000a.lzy.p004a.ProgressListener
                public void onError(Progress progress) {
                    int i;
                    String str;
                    SendModel.this.isError = true;
                    OkUpload.getInstance().removeAll();
                    Throwable th = progress.exception;
                    if (th != null) {
                        th.printStackTrace();
                        String str2 = SendModel.this.TAG;
                        LogUtils.m63e(str2, progress.tag + "onError:" + th.getMessage());
                        String message = th.getMessage();
                        if (TextUtils.isEmpty(message) || !message.contains("Android/data/com.grass.pomegranate/files")) {
                            try {
                                str = JsonUtils.getString(NotificationCompat.CATEGORY_MESSAGE, message);
                                i = JsonUtils.getInt("code", message);
                            } catch (Exception unused) {
                                i = 112;
                                str = th instanceof SocketTimeoutException ? "連接超時" : "其它錯誤";
                            }
                            SendModel.this.data.setValue(new BaseRes(i, str));
                        } else {
                            SendModel.this.addUploadTask();
                            return;
                        }
                    } else {
                        SendModel.this.data.setValue(new BaseRes(885, "未知錯誤"));
                    }
                    for (CutBean cutBean : SendModel.this.list) {
                        File file = new File(cutBean.getPath());
                        if (file.exists()) {
                            file.delete();
                        }
                    }
                    SendModel.this.delete();
                }

                public void onFinish(BaseRes<SendVideoBean> baseRes, Progress progress) {
                    SendModel.this.finish(baseRes, progress);
                }
            });
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void progress(Progress progress) {
        float f = 0.0f;
        for (int i = 0; i < this.list.size(); i++) {
            CutBean cutBean = this.list.get(i);
            if (cutBean.getTag() == Integer.parseInt(progress.tag)) {
                cutBean.setProgressNum(progress.fraction);
            }
            f += cutBean.getProgressNum();
        }
        int size = (int) ((f / ((float) this.list.size())) * 100.0f);
        BaseRes<SendVideoBean> baseRes = new BaseRes<>(1000001, "");
        SendVideoBean sendVideoBean = new SendVideoBean();
        sendVideoBean.setProgressNum((float) size);
        baseRes.setData(sendVideoBean);
        if (!this.isError) {
            this.data.setValue(baseRes);
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void finish(BaseRes<SendVideoBean> baseRes, Progress progress) {
        int i = 0;
        for (int i2 = 0; i2 < this.list.size(); i2++) {
            CutBean cutBean = this.list.get(i2);
            if (cutBean.getTag() == Integer.parseInt(progress.tag)) {
                cutBean.setFinish(true);
                String str = this.TAG;
                LogUtils.m63e(str, "删除文件地址：" + cutBean.getPath());
            }
            if (cutBean.isFinish()) {
                i++;
            }
        }
        if (i == this.list.size()) {
            OkUpload.getInstance().removeAll();
            baseRes.getData().setSize(this.file.length());
            baseRes.getData().setCheckSum(this.fileMD5);
            videoOk(baseRes);
            delete();
            for (CutBean cutBean2 : this.list) {
                File file2 = new File(cutBean2.getPath());
                if (file2.exists()) {
                    file2.delete();
                }
            }
        }
    }

    private <T> void post_form(String str, File file2, String str2, int i, HttpCallback<BaseRes<SendVideoBean>> httpCallback, UploadListener<BaseRes<SendVideoBean>> uploadListener) {
        LogUtils.m63e("ddddddddddddd", file2.getPath() + "<--->" + file2.length());
        PostRequest postRequest = (PostRequest) ((PostRequest) ((PostRequest) ((PostRequest) ((PostRequest) ((PostRequest) ((PostRequest) ((PostRequest) ((PostRequest) OkGo.post(str).isMultipart(true)).tag(httpCallback.getTag())).client(this.okHttpClient)).params("file", file2)).params("pos", i, new boolean[0])).params("taskId", str2, new boolean[0])).headers(HttpHeaders.HEAD_KEY_CONTENT_TYPE, "application/json")).headers(HttpHeaders.HEAD_KEY_ACCEPT, "application/json")).converter(httpCallback);
        String string = SpUtils.getInstance().getString(Key.TOKEN);
        if (!TextUtils.isEmpty(string)) {
            postRequest.headers("Authorization", string);
        }
        if (!TextUtils.isEmpty(BaseSdk.UserAgent)) {
            postRequest.headers(HttpHeaders.HEAD_KEY_USER_AGENT, BaseSdk.UserAgent);
        }
        String valueOf = String.valueOf(System.currentTimeMillis());
        String substring = valueOf.substring(3, 8);
        postRequest.headers("t", valueOf);
        try {
            String md5 = FileListUtils.getMD5(substring);
            postRequest.headers("s", md5 + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        postRequest.headers("deviceId", DeviceIDUtils.getUniqueId(BaseSdk.getContext()));
        LogUtils.m63e("ddddddddddddd", file2.getPath() + "<--->" + file2.length());
        StringBuilder sb = new StringBuilder();
        sb.append("");
        sb.append(i);
        UploadTask<T> save = OkUpload.request(sb.toString(), postRequest).save();
        save.register(uploadListener);
        save.start();
    }

    public void videoOk(final BaseRes<SendVideoBean> baseRes) {
        HttpUtils.getInsatance().post(UrlManager.getInsatance().videoOk(), new Gson().toJson(new ReqVideoOkBen(this.fileMD5, baseRes.getData().getId(), this.file.getName(), IcyHeaders.REQUEST_HEADER_ENABLE_METADATA_VALUE)), new HttpCallback<BaseRes<String>>("VideoOk") {
            /* class com.grass.appointment.model.SendModel.C28524 */

            public void onLvSuccess(BaseRes<String> baseRes) {
                baseRes.setCode(baseRes.getCode());
                SendModel.this.data.setValue(baseRes);
            }
        });
    }

    public void submit(ReqAddVideoBean reqAddVideoBean) {
        HttpUtils.getInsatance().post(UrlManager.getInsatance().addVideo(), new Gson().toJson(reqAddVideoBean), new HttpCallback<BaseRes<AddVideoBean>>("AddVideo") {
            /* class com.grass.appointment.model.SendModel.C28535 */

            public void onLvSuccess(BaseRes<AddVideoBean> baseRes) {
                SendModel.this.addViewData.setValue(baseRes);
            }
        });
    }
}
